import React, {
  forwardRef, useEffect, useImperativeHandle, useState,
} from 'react'
import {
  Button,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Radio,
  Row,
  Select,
  Tooltip,
  TreeSelect,
} from 'antd'
import { connect, history } from '@umijs/max'
import list2tree from 'list2tree'
import { regExp } from '@/utils/regExp.js'
import styles from './index.less'

const { Option } = Select
const descRe = regExp.nameCN(1, 128)
const enNameRe = regExp.characteristic(1, 128)

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'key',
    value: 'id',
    title: 'name',
  },
})

/**
 * 处理分组函数
 * @param {} arr
 */
const allCatalogFn = (arr) => {
  arr.map((item) => {
    item.title = item.themeName
    item.groupName = item.themeName
    item.value = item.id
    item.key = item.id
    item.children && item.children.length
      ? allCatalogFn(item.children)
      : null
    return null
  })
}

let featureIndex = 0
let enumIndex = 0

const projectId = JSON.parse(sessionStorage.getItem('defaultWorkSpace') || '{}').id

const CreateStandard = (props) => {
  const [modalVisible, setModalVisible] = useState(false)
  const [serviceFeature, setServiceFeature] = useState([])
  const [enumRange, setEnumRange] = useState([])
  const [treeData, setTreeData] = useState([])
  const [dataTypeList, setDataTypeList] = useState([])
  const [unitMeasureList, setUnitMeasureList] = useState([])
  // const [departmentOptions, setDepartmentOptions] = useState([])
  const [disabled, setDisabled] = useState(false)
  const [editId, setEditId] = useState('')
  const [dictionaryList, setDictionaryList] = useState([])
  const [saveLoading, setSaveLoading] = useState(false)
  const [publishLoading, setPublishLoading] = useState(false)

  const [form] = Form.useForm()

  useEffect(() => {
    getGroupList()
    getDictCons()
    // getDepartmentList()
  }, [])

  useEffect(() => {
    modalVisible && getGroupList()
    // modalVisible && getDepartmentList()
  }, [modalVisible])

  // useEffect(() => {
  //   if (props.dictionaryList.length > 0 && dictionaryList.length <= 0) {
  //     const tempData = getNavTreeDataFunc(props.dictionaryList) || []
  //     allCatalogFn(tempData)
  //     setTreeData(tempData)
  //     setDictionaryList(props.dictionaryList)
  //   }
  // })

  useImperativeHandle(props.refInstance, () => ({
    toggleModal,
  }))

  // 获取字典目录分组
  const getGroupList = () => {
    props.dispatch({
      type: 'standardDefine/dictionaryGroupList',
      cb: (data) => {
        const tempData = getNavTreeDataFunc(data) || []
        allCatalogFn(tempData)
        // setTreeData([
        //   {
        //     title: '全部分组',
        //     groupName: '全部分组',
        //     value: 0,
        //     key: 0,
        //     id: 0,
        //     children: tempData,
        //   },
        // ])
        setTreeData(tempData)
        setDictionaryList(data || [])
      },
    })
  }

  // 获取查看字典详情内的一些常量选项
  const getDictCons = () => {
    props.dispatch({
      type: 'standardDefine/consList',
      cb: (data) => {
        setDataTypeList(data.dataTypeList)
        setUnitMeasureList(data.unitMeasureList)
      },
    })
  }

  const toggleModal = (detail = {}, editStaParams = false) => {
    setDisabled(editStaParams)
    if (Object.keys(detail).length > 0) {
      const { bizPropertiesJson, dictDataEnumValueJson, dictDataRangeJson } = detail || {}
      const featureArr = bizPropertiesJson && JSON.parse(bizPropertiesJson) || []
      const enumArr = dictDataEnumValueJson && JSON.parse(dictDataEnumValueJson) || []
      const dictDataRangeJsonTemp = dictDataRangeJson && JSON.parse(dictDataRangeJson) || {}

      const serviceFeatureTemp = []
      const fieldObj = {}
      featureArr.map((item, index) => {
        const obj = {
          keyName: `featureKey-${index}`,
          valueName: `featureValue-${index}`,
        }
        fieldObj[`featureKey-${index}`] = item.key
        fieldObj[`featureValue-${index}`] = item.value
        serviceFeatureTemp.push(obj)
        return null
      })

      const enumFeatureTemp = []
      enumArr.map((item, index) => {
        const obj = {
          keyName: `enumKey-${index}`,
          valueName: `enumValue-${index}`,
        }
        fieldObj[`enumKey-${index}`] = item.key
        fieldObj[`enumValue-${index}`] = item.value
        enumFeatureTemp.push(obj)
        return null
      })

      featureIndex = serviceFeatureTemp.length
      setServiceFeature(serviceFeatureTemp)
      setEnumRange(enumFeatureTemp)
      setEditId(detail.id)

      form.setFieldsValue({ ...detail, ...fieldObj, ...dictDataRangeJsonTemp })
    }
    if (modalVisible) {
      form.resetFields()
      setServiceFeature([])
      setEnumRange([])
      setSaveLoading(false)
      setPublishLoading(false)
    }
    setModalVisible(!modalVisible)
  }

  // 添加业务属性
  const addServiceFeature = () => {
    if (disabled) {
      return null
    }
    const obj = {
      keyName: `featureKey-${featureIndex}`,
      valueName: `featureValue-${featureIndex}`,
    }
    setServiceFeature(
      [
        ...serviceFeature,
        obj,
      ],
    )
    featureIndex += 1
    return null
  }

  // 删除业务属性
  const deleteServiceFeature = (index) => {
    if (disabled) return null
    const serviceFeatureCopy = [...serviceFeature]
    serviceFeatureCopy.splice(index, 1)
    setServiceFeature(serviceFeatureCopy)
    return null
  }

  // 添加枚举
  const addEnumRange = () => {
    if (disabled) return null
    const obj = {
      keyName: `enumKey-${enumIndex}`,
      valueName: `enumValue-${enumIndex}`,
    }
    setEnumRange(
      [
        ...enumRange,
        obj,
      ],
    )
    enumIndex += 1
    return null
  }

  // 删除枚举
  const deleteEnumRange = (index) => {
    if (disabled) return null
    const enumRangeCopy = [...enumRange]
    enumRangeCopy.splice(index, 1)
    setEnumRange(enumRangeCopy)
    return null
  }

  // 保存
  const save = (isPublic) => {
    if (isPublic) {
      setPublishLoading(true)
    } else {
      setSaveLoading(true)
    }

    form.validateFields().then(values => {
      const {
        dictNameCn, dictNameEn, dictDirId, dictDataType, dictDataLength, dictDataUnit, allowNull, allowDuplicate, dictDataPattern, departmentId, valueCondition1, valueRange1, valueJudge, valueCondition2, valueRange2,
      } = values
      const featureArr = []
      const enumArr = []
      for (const item in values) {
        if (item.indexOf('featureKey') !== -1) {
          const obj = {
            key: values[item],
            value: values[`featureValue-${item?.split('-')[1]}`],
          }
          featureArr.push(obj)
        }
        if (item.indexOf('enumKey') !== -1) {
          const obj = {
            key: values[item],
            value: values[`enumValue-${item?.split('-')[1]}`],
          }
          enumArr.push(obj)
        }
      }

      const params = {
        bizPropertiesJson: JSON.stringify(featureArr),
        dictDataEnumValueJson: JSON.stringify(enumArr),
        dictDataRangeJson: JSON.stringify({
          valueCondition1,
          valueRange1,
          valueJudge,
          valueCondition2,
          valueRange2,
        }),
      }

      const reqType = disabled === 0 ? 'dictionaryEdit' : 'dictionaryAdd'
      const id = disabled === 0 ? editId : null

      props.dispatch({
        type: `standardDefine/${reqType}`,
        params: {
          id,
          dictNameCn,
          dictNameEn,
          dictDirId,
          dictDataType,
          dictDataLength,
          dictDataUnit,
          allowNull,
          allowDuplicate,
          dictDataPattern,
          // departmentId,
          dictType: 0, // 字典类型 默认值为 0
          releaseStatus: isPublic ? 1 : 0,
          ...params,
        },
        cb: (data) => {
          const { msg, status } = data
          if (isPublic) {
            setPublishLoading(false)
          } else {
            setSaveLoading(false)
          }
          if (status === 200) {
            toggleModal()
            props.forceUpdateFn()
          } else {
            message.error(msg || '服务端错误')
          }
        },
      })
    }).catch(errorInfo => {
      if (isPublic) {
        setPublishLoading(false)
      } else {
        setSaveLoading(false)
      }
      console.log('errorInfo', errorInfo)
    })
  }

  // 获取归属部门选项
  // const getDepartmentList = () => {
  //   props.dispatch({
  //     type: 'standardDefine/departmentList',
  //     params: {
  //       // projectId: '61e61a8e49c0e3729a1724b9',
  //       projectId,
  //     },
  //     cb: (data) => {
  //       setDepartmentOptions(data)
  //     },
  //   })
  // }

  const calcTitle = () => {
    let title = '新建'
    if (disabled) {
      title = '查看'
    } else if (disabled === 0) {
      title = '编辑'
    }
    return title
  }

  return (
    <Modal
      className={styles.create_standard}
      title={`${calcTitle()}标准`}
      visible={modalVisible}
      maskClosable={false}
      forceRender={false}
      bodyStyle={{
        height: `${document.documentElement.clientHeight * 0.65}px`,
        overflowY: 'auto',
      }}
      width={520}
      footer={[
        <Button key={1} onClick={toggleModal}>取消</Button>,
        <Button key={2} loading={saveLoading} disabled={disabled} onClick={() => { save(false) }}>保存</Button>,
        <Button key={3} loading={publishLoading} disabled={disabled} onClick={() => { save(true) }} type="primary">发布</Button>,
      ]}
      onCancel={toggleModal}
    // onOk={onConfirm}
    >
      <Form
        form={form}
        className={styles.form}
        name="basic"
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 19 }}
        initialValues={{ remember: true }}
        // onFinish={onFinish}
        // onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item>
          <div className={styles.column}>基础属性</div>
        </Form.Item>
        <Form.Item
          label="中文名称"
          name="dictNameCn"
          rules={[
            { required: true, message: '请输入中文名称' },
            {
              pattern: new RegExp(descRe.reg, 'g'),
              message: descRe.text,
            },
          ]}
        >
          <Input disabled={disabled} placeholder="请输入中文名称" />
        </Form.Item>
        <Form.Item
          label="英文名称"
          name="dictNameEn"
          rules={[
            { required: true, message: '请输入英文名称' },
            {
              pattern: new RegExp(enNameRe.reg, 'g'),
              message: enNameRe.text,
            },
          ]}
        >
          <Input disabled={disabled} placeholder="请输入英文名称" />
        </Form.Item>
        <Form.Item
          label="字典目录"
          name="dictDirId"
          rules={[{ required: true, message: '请选择字典目录' }]}
        >
          <TreeSelect
            placeholder="请选择字典目录"
            treeData={treeData}
            disabled={disabled}
            getPopupContainer={(triggerNode) => triggerNode.parentNode}
          />
        </Form.Item>
        <Form.Item>
          <div className={styles.column}>业务属性
            <Tooltip
              placement="topRight"
              title={
                <div>
                  <p>业务属性为KV形式，以”设备编码“标准为例，业务属性可填写：</p>
                  <p>编码规则：sbbh（固定值）+ 时间戳组合、</p>
                  <p>应用范围：仅限于设备表使用、</p>
                  <p>业务描述：用来区分设备，是设备的唯一识别号</p>
                </div>
              }
            ><i className="iconfont icon-yiwentishi" />
            </Tooltip>
          </div>
          <span className={`${styles.add_btn} ${disabled ? styles.disabled : ''}`} onClick={addServiceFeature}><i className="iconfont icon-tianjia1" />添加属性</span>
        </Form.Item>
        {
          serviceFeature.length > 0 && (
            <Form.Item
              className={styles.item_margin}
              colon={false}
              label=" "
            >
              <>
                {
                  serviceFeature.map((item, index) => (
                    <Row key={index}>
                      <Col span={10}>
                        <Form.Item
                          name={item.keyName}
                          // initialValue={serviceFeature[index]}
                          rules={
                            [{ required: true, message: '请输入属性项' }]
                          }
                        >
                          <Input disabled={disabled} placeholder="请输入属性项" />
                        </Form.Item>
                      </Col>
                      <Col span={1} className={styles.mark}>
                        <span>:</span>
                      </Col>
                      <Col span={10}>
                        <Form.Item
                          name={item.valueName}
                          rules={
                            [{ required: true, message: '请输入属性值' }]
                          }
                        >
                          <Input disabled={disabled} placeholder="请输入属性值" />
                        </Form.Item>
                      </Col>
                      <Col span={3} className={styles.icon}>
                        <i className={`iconfont icon-shanchu ${disabled ? styles.disabled : ''}`} onClick={() => { deleteServiceFeature(index) }} />
                      </Col>
                    </Row>
                  ))
                }
              </>
            </Form.Item>
          )
        }
        <Form.Item>
          <div className={styles.column}>数据属性</div>
        </Form.Item>
        <Form.Item
          label="数据类型"
          name="dictDataType"
          rules={[{ required: true, message: '请选择数据类型' }]}
        >
          <Select
            disabled={disabled}
            placeholder="请选择数据类型"
            getPopupContainer={(triggerNode) => triggerNode.parentNode}
          >
            {dataTypeList && dataTypeList.map((item, index) => (
              <Option value={item.key} key={index}>
                {`${item.value}(${item.key})`}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="数据长度"
          name="dictDataLength"
        // rules={[{ required: true, message: '请选择数据长度' }]}
        >
          <InputNumber disabled={disabled} precision={0} min={1} max={2147483647} />
        </Form.Item>
        <Form.Item
          label="度量单位"
          name="dictDataUnit"
        >
          <Select
            disabled={disabled}
            placeholder="请选择度量单位"
            getPopupContainer={(triggerNode) => triggerNode.parentNode}
          >
            {unitMeasureList.map((item, index) => (
              <Option value={item.key} key={index}>
                {`${item.value}(${item.key})`}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="是否允许为空"
          name="allowNull"
          initialValue={1}
        >
          <Radio.Group disabled={disabled}>
            <Radio value={1} key="1">是</Radio>
            <Radio value={0} key="0">否</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="是否允许重复"
          name="allowDuplicate"
          initialValue={1}
        >
          <Radio.Group disabled={disabled}>
            <Radio value={1} key="1">是</Radio>
            <Radio value={0} key="0">否</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="取值范围"
        >
          <div>
            <Form.Item name="valueCondition1" className={styles.select_wrap}>
              <Select disabled={disabled}>
                <Option value=">" key="0"> &gt; </Option>
                <Option value="<" key="1"> &lt; </Option>
                <Option value="=" key="2"> = </Option>
              </Select>
            </Form.Item>
            <Form.Item name="valueRange1" className={styles.input_wrap}>
              <Input disabled={disabled} type="number" />
            </Form.Item>
            <Form.Item name="valueJudge" className={styles.select_value_wrap}>
              <Select disabled={disabled}>
                <Option value="or" key="0">或</Option>
                <Option value="and" key="1">且</Option>
                <Option value="!" key="2">非</Option>
              </Select>
            </Form.Item>
            <Form.Item name="valueCondition2" className={styles.select_value_wrap}>
              <Select disabled={disabled}>
                <Option value=">" key="0">
                  {'>'}
                </Option>
                <Option value="<" key="1">
                  {'<'}
                </Option>
                <Option value="=" key="2">
                  =
                </Option>
              </Select>
            </Form.Item>
            <Form.Item name="valueRange2" className={styles.input_value_wrap}>
              <Input disabled={disabled} type="number" placeholder="请输入数值" />
            </Form.Item>
          </div>
        </Form.Item>
        <Form.Item
          label="枚举范围"
        >
          <span className={`${styles.add_btn} ${disabled ? styles.disabled : ''}`} onClick={addEnumRange}><i className="iconfont icon-tianjia1" />添加枚举</span>
        </Form.Item>
        {
          enumRange.length > 0 && (
            <Form.Item
              className={styles.item_margin}
              colon={false}
              label=" "
            >
              {
                enumRange.map((item, index) => (
                  <Row key={index}>
                    <Col span={10}>
                      <Form.Item
                        name={item.keyName}
                        // initialValue={serviceFeature[index]}
                        rules={
                          [{ required: true, message: '请输入枚举值' }]
                        }
                      >
                        <Input disabled={disabled} placeholder="请输入枚举值" />
                      </Form.Item>
                    </Col>
                    <Col span={1} className={styles.mark}>
                      <span>:</span>
                    </Col>
                    <Col span={10}>
                      <Form.Item
                        name={item.valueName}
                        rules={
                          [{ required: true, message: '请输入枚举含义' }]
                        }
                      >
                        <Input disabled={disabled} placeholder="请输入枚举含义" />
                      </Form.Item>
                    </Col>
                    <Col span={3} className={styles.icon}>
                      <i className={`iconfont icon-shanchu ${disabled ? styles.disabled : ''}`} onClick={() => { deleteEnumRange(index) }} />
                    </Col>
                  </Row>
                ))
              }
            </Form.Item>
          )
        }

        <Form.Item
          label="正则表达式"
          name="dictDataPattern"
        >
          <Input disabled={disabled} placeholder="请输入正则表达式" />
        </Form.Item>
        <Form.Item>
          <div className={styles.column}>管理属性</div>
        </Form.Item>
        {/* <Form.Item
          label="数据owner"
          name="departmentId"
          rules={[{ required: true, message: '请选择数据类型' }]}
        >
          <Select
            disabled={disabled}
            placeholder="请选择数据owner"
            getPopupContainer={(triggerNode) => triggerNode.parentNode}
            dropdownRender={(menu) => (
              <div>
                {menu}
                <Divider className={styles.divider} />
                <div
                  className={styles.select_dropdown}
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => { history.push('/standard-design/dataSurvey/dataOwner') }}
                >
                  <i
                    className="iconfont icon-tianjia"
                  />
                  <span>新建Owner</span>
                </div>
              </div>
            )}
          >
            {departmentOptions.length > 0 && departmentOptions.map((item, index) => (
              <Option value={item.id} key={index}>
                {item.ownerName}
              </Option>
            ))}
          </Select>
        </Form.Item> */}
      </Form>
    </Modal>
  )
}

const IComponent = connect(({ standardDefine }) => ({ ...standardDefine }))(CreateStandard)

export default forwardRef((props, ref) => <IComponent {...props} refInstance={ref} />)
